<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Web Request Tool</title>
    <!-- Bootstrap core CSS -->
    <link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <style>
        form {
            padding: 30px;
        }
        h1{ text-align: center  }
        .list-group-item{padding: 6px 4px; font-size: 12px;}
        .history-item span{cursor: pointer}
        .history-item span:first-child:hover{padding-left:5px; border-left: #FF9966 4px solid; color: #000000;}
    </style>
</head>
<body>
<div class="row" style="margin-right:0;">
    <div class="col-lg-7">
        <h1>WEB REQUEST TOOL</h1>
        <form class="form-group" name="request" method="post" onsubmit="javascript:void(0)" >
            <div class="form-group">
                <div class="col-md-7">
                    <div class="input-group">
                        <div class="input-group-addon">NOTE</div>
                        <input name="note" class="form-control" placeholder="备注...">
                    </div>
                </div>
                <div class="col-md-5">
                    <div class="col-md-7">
                        <div class="input-group">
                            <div class="input-group-addon">METHOD</div>
                            <select name="type" class="form-control"><option value="POST">POST</option><option value="GET">GET</option><option value="RAW">RAW</option></select>
                        </div>
                    </div>
                    <div class="col-md-5">
                        <div class="input-group">
                            <div class="input-group-addon">TYPE</div>
                            <select name="datatype" class="form-control"><option value="text">text</option><option value="json">json</option><option value="params">params</option></select>
                        </div>
                    </div>
                </div>
            </div>
            <br>
            <br>
            <div class="form-group">
                <div class="col-md-12">
                    <div class="input-group">
                        <div class="input-group-addon">URL</div>
                        <input name="url" class="form-control" required="true" placeholder="http://" />
                    </div>
                </div>
            </div>
            <br>
            <br>
            <div class="form-group">
                <div class="col-md-12">
                    <div class="input-group">
                        <div class="input-group-addon">PARAMS</div>
                        <textarea name="params" class="form-control" rows="2" required="true" placeholder="param1=val1&param2=val2"></textarea>
                    </div>
                </div>
            </div>
            <br>
            <br>
            <br>
            <div class="form-group">
                <div class="col-md-12">
                    <div class="input-group">
                        <div class="input-group-addon">Cookie</div>
                        <input name="cookie" class="form-control" required="true" placeholder="a=b;c=d;" />
                    </div>
                </div>
            </div>
            <br>
            <br>
            <div class="form-group">
                <div class="col-md-12">
                    <div class="input-group">
                        <div class="input-group-addon">Authorization</div>
                        <input name="auth" class="form-control" required="true" placeholder="name:pwd" >
                    </div>
                </div>
            </div>
            <br>
            <br>
            <div class="form-group">
                <div class="col-md-12">
                    <button type="button" id="request-btn" class="btn btn-primary btn-block">Request</button>
                </div>
            </div>
        </form>
        <div class="row">
            <div style="margin:0 6%;">
                <a href="#" class="list-group-item" style="background-color:#EEEEEE; font-size: 14px; line-height: 20px; color:#FF9966;">
                    <span style="font-size: 24px; font-weight: normal; vertical-align: top;">&#x2709;</span> HISTORY
                </a>
                <ul class="list-group" id="history-body">
                </ul>
            </div>
            <div class="col-lg-1"></div>
        </div>
    </div>
    <div class="col-lg-5">
            <textarea id="result"  style="margin-top: 20px; width: 100%; font-size:12px; color: #555; border:1px dotted silver" placeholder="Request Result" ></textarea>
    </div>
</div>

<!-- Placed at the end of the document so the pages load faster -->
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script language="JavaScript">


    // 初始化数据库和表
    var db = initDB();
    createTables(db);

    // 加载默认数据
    fillData(getLog(db));

    // 加载默认历史记录
    getHistoryLog(db);

    // 全局数据
    var tmp_global_data = "";


    $(document).ready(function(e){
        $("#result").css('height',$(document).height() - 50);
        $("#request-btn").click(function(){
            var note = $("input[name=note]").val();
            var type = $("select[name=type]").val();
            var url = $("input[name=url]").val();
            var cookie = $("input[name=cookie]").val();
            var auth = $("input[name=auth]").val();
            var params = $("textarea[name=params]").val();
            var datatype = $("select[name=datatype]").val();
            if(note == ""){
                note = url;
            }
            var request_obj = {
                note:note,
                type:type,
                url:url,
                cookie:cookie,
                auth:auth,
                params:params,
                datatype:datatype
            };
            $.ajax({
                url:"request.php",
                type:"POST",
                dataType:"text",
                data:request_obj,
                cache:false,
                beforeSend:function(){
                    $("#result").val("正在请求...");
                },
                success:function(data){
                    $("#result").val(data);

                    // 记录日志
                    json_data = JSON.stringify(request_obj);
                    if(tmp_global_data != json_data){
                        tmp_global_data = json_data;
                        addData(db, json_data, data);

                        //刷新历史记录
                        getHistoryLog(db);
                    }
                },
                error:function(xhr,st,exp){
                    $("#result").val("请求错误： "+st);
                }
            });
        });
    });

    // 创建数据库
    function initDB(){
        var myDB = null;
        try {
            if (!window.openDatabase) {
                // 当前浏览器没有数据库支持
                alert('db not supported');
            } else {
                var shortName = 'log_db';
                var version = '1.0';
                var displayName = 'test offline database';
                var maxSize = 65536; // 字节
                myDB = openDatabase(shortName, version, displayName, maxSize);
            }
        } catch(e) {
            // 这里开始异常处理 .
            if (e == INVALID_STATE_ERR) {
                // 数据库版本异常 .
                alert("Invalid database version.");
            } else {
                alert("Unknown error "+e+".");
            }
        }
        // 返回创建好的数据库实例
        return myDB;
    }

    // 创建表结构
    function createTables(db){
        db.transaction(
                function (transaction) {
                    transaction.executeSql('CREATE TABLE IF NOT EXISTS request_log(id INTEGER, content TEXT, result_data TEXT);',
                            [], function(result){}, function(tx,error){
                                console.log(error);
                            });
                }
        );
    }

    // 添加数据
    function addData(db, content, result_data){
        // 先删除相同的数据
        deleteSameData(content);

        // 再执行添加
        db.transaction(
                function (transaction) {
                    var timestamp=new Date().getTime();
                    var id = timestamp.toString().substr(0, 10);
                    transaction.executeSql('INSERT INTO request_log values(?,?,?)',[id, content, result_data],
                    function(result){

                    },
                    function(tx,error){

                    }
                    );
                })
    }

    // 查询最近的一条数据
    function getLog(db){
        db.transaction(
                function (transaction) {
                    transaction.executeSql('SELECT * FROM request_log ORDER BY rowid DESC LIMIT 1', [],
                            function(tx, result){
                                if(result.rows.length > 0){
                                   var first_row = JSON.parse(result.rows.item(0).content);
                                    fillData(first_row, result.rows.item(0).result_data);
                                }
                            }, function(tx,error){});
                });
    }


    // 查询最近的100条数据
    function getHistoryLog(db){
        db.transaction(
                function (transaction) {
                    transaction.executeSql('SELECT * FROM request_log ORDER BY rowid DESC LIMIT 100', [],
                            function(tx, result){
                                if(result.rows.length > 0){

                                        //先清空历史记录
                                    $("#history-body").html("");

                                    for(var i = 0; i < result.rows.length; i++){
                                        var row_obj = JSON.parse(result.rows.item(i).content);

                                        // 填充历史记录
                                        fillHistoryData(row_obj, result.rows.item(i).id);
                                    }
                                }
                            }, function(tx,error){});
                });
    }

    // 删除相同数据
    function deleteSameData(content){
        db.transaction(function(tx){
            tx.executeSql("DELETE FROM request_log WHERE content = ?" ,
                    [content],
                    function(tx, result){
                        console.log("delete " + result.rowsAffected + ' same records');
                    }
            );
        });
    }

    // 删除指定id数据
    function deleteDataById(id){
        db.transaction(function(tx){
            tx.executeSql("DELETE FROM request_log WHERE id = ?" ,
                    [id],
                    function(tx, result){
                        console.log("delete " + result.rowsAffected + ' same records');
                    }
            );
        });
    }

    // 填充数据
    function fillData(row_obj, result_data){
        if(row_obj != null){
            $("select[name=type]").val(row_obj.type);
            $("input[name=note]").val(row_obj.note);
            $("input[name=url]").val(row_obj.url);
            $("input[name=cookie]").val(row_obj.cookie);
            $("input[name=auth]").val(row_obj.auth);
            $("textarea[name=params]").val(row_obj.params);
            $("select[name=datatype]").val(row_obj.datatype);
            $("#result").val(result_data);

        }
    }

    // 历史数据显示
    function fillHistoryData(row_obj, id){
        var html = ' <li class="list-group-item history-item" id="item' + id + '" ><span onClick="showHistoryData(' + id + ')"><b style="color: #ffaf3d;">'+ row_obj.type + "</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + row_obj.note + '<b>(' + row_obj.datatype + ')</b></span><span class="pull-right" onClick="deleteHistoryData(' + id + ')">&#x2716;</span><span class="pull-right" style="color:#AAAAAA;">' + getDateDiff(id) + '&nbsp;&nbsp;&nbsp;&nbsp;</span></li>';
        $("#history-body").html($("#history-body").html() + html);
    }

    // 历史数据渲染
    function showHistoryData(id){
        db.transaction(
                function (transaction) {
                    transaction.executeSql('SELECT * FROM request_log WHERE id = ? LIMIT 1', [id],
                            function(tx, result){
                                if(result.rows.length > 0){
                                    var row_obj = JSON.parse(result.rows.item(0).content);
                                    fillData(row_obj, result.rows.item(0).result_data);
                                }
                            }, function(tx,error){});
                });
    }

    // 历史数据删除
    function deleteHistoryData(id){
        var st = this.window.confirm("确定删除吗");
        if(st){

            // 数据库中删除
            deleteDataById(id);

            // 删除节点
            var id_name = "#item" + id;
            $(id_name).remove();

        }
    }

    function getDateDiff(dateTimeStamp){
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - dateTimeStamp*1000;
        var monthC =diffValue/month;
        var weekC =diffValue/(7*day);
        var dayC =diffValue/day;
        var hourC =diffValue/hour;
        var minC =diffValue/minute;
        if(monthC>=1){
            result= parseInt(monthC) + "月前";
        }
        else if(weekC>=1){
            result = parseInt(weekC) + "周前";
        }
        else if(dayC>=1){
            result = parseInt(dayC) +"天前";
        }
        else if(hourC>=1){
            result = parseInt(hourC) +"小时前";
        }
        else if(minC>=1){
            result= parseInt(minC) +"分钟前";
        }else
            result="刚刚";
        return result;
    }

</script>
</body>
</html>